package by.grsu.coctails.db;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import by.grsu.coctails.common.utils.FileUtils;
import by.grsu.coctails.common.utils.Log;
import by.grsu.coctails.db.tables.CoctailsTable;

/**
 * The Class DBHelper.
 */
public class DBHelper extends SQLiteOpenHelper {

	private static final String TAG = DBHelper.class.getSimpleName();

	private String DB_DIR;

	private String DB_NAME;

	private Context mContext;

	private SQLiteDatabase coctailDataBase;

	public DBHelper(final Context context, String name, final int version) {
		super(context, name, null, version);
		this.mContext = context;
		DB_DIR = "data/data/" + context.getPackageName() + "/databases/";
		DB_NAME = name;

	}

	@Override
	public final void onCreate(final SQLiteDatabase db) {

	}

	@Override
	public final void onUpgrade(final SQLiteDatabase db, final int oldVersion,
			final int newVersion) {
	}

	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (!dbExist) {
			// this.getReadableDatabase();
			copyDataBase();
		}

	}

	private boolean checkDataBase() {

		SQLiteDatabase checkDB = null;

		try {
			String path = DB_DIR + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(path, null,
					SQLiteDatabase.OPEN_READONLY);

			if (checkDB != null) {
				Cursor cursor = checkDB.query(CoctailsTable.NAME, null, null, null,
						null, null, null);
				return cursor.moveToFirst();

			}
		} catch (SQLiteException e) {
			Log.e(TAG, "data base not found", e);

		} finally {
			if (checkDB != null) {
				checkDB.close();
			}
		}

		return false;
	}

	private void copyDataBase() throws IOException {

		InputStream dbInput = mContext.getAssets().open(DB_NAME);

		String outFileName = DB_DIR + DB_NAME;

		OutputStream dbOutput = new FileOutputStream(outFileName);

		FileUtils.copyFile(dbInput, dbOutput);

	}

	public void openDataBase() throws SQLException {

		String myPath = DB_DIR + DB_NAME;
		coctailDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READONLY);

	}

	@Override
	public synchronized void close() {

		if (coctailDataBase != null)
			coctailDataBase.close();

		super.close();

	}

}
